package com.xavier.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xavier.dao.RoleMenuMapper;
import com.xavier.model.RoleMenu;
import com.xavier.service.IRoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 业务逻辑层-角色菜单实现类
 *
 * @author Xavier
 * @version 1.0
 */
@Slf4j
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createRoleMenu(Long roleId, List<Long> menuIds) {
        if (ObjectUtil.isEmpty(menuIds)) {
            return;
        }
        List<RoleMenu> beanList = new ArrayList<>();
        for (Long menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            beanList.add(roleMenu);
        }
        super.saveBatch(beanList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleMenu(Long roleId, List<Long> menuIds) {
        remove(RoleMenu.gw().eq(RoleMenu::getRoleId, roleId));
        createRoleMenu(roleId, menuIds);
    }

    @Override
    public List<Long> getRoleMenu(Long roleId) {
        List<RoleMenu> list = list(RoleMenu.gw().eq(RoleMenu::getRoleId, roleId));
        return ObjectUtil.isEmpty(list) ? null : list.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
    }


}
